<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/hexo/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/hexo/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/hexo/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/hexo/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/hexo/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/hexo/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/hexo/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="经验分享,">










<meta name="description" content="最近公司赶项目，由于时间，人手等问题，经理武断的决定把一个本来要做成app的项目做成手机web网站的形式。。。然后还把这个项目交给了一个后端开发人员（没错就是我(┬＿┬)）。。。在做这个项目的是，由于采用的是webapi的形式和服务器交互，所以，这个手机web网站就是纯前端的东西，html+js。由于我对前端的项目部署方案不太了解，当我们需要把文件部署到服务器上测试的时候，每次都要远程连接服务器然">
<meta name="keywords" content="经验分享">
<meta property="og:type" content="article">
<meta property="og:title" content="一个简单的socket小工具">
<meta property="og:url" content="https://tony_df.coding.net/2018/10/08/一个简单的socket小工具/index.html">
<meta property="og:site_name" content="Tony&#39;s blog">
<meta property="og:description" content="最近公司赶项目，由于时间，人手等问题，经理武断的决定把一个本来要做成app的项目做成手机web网站的形式。。。然后还把这个项目交给了一个后端开发人员（没错就是我(┬＿┬)）。。。在做这个项目的是，由于采用的是webapi的形式和服务器交互，所以，这个手机web网站就是纯前端的东西，html+js。由于我对前端的项目部署方案不太了解，当我们需要把文件部署到服务器上测试的时候，每次都要远程连接服务器然">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://tony_df.coding.net/2018/10/08/一个简单的socket小工具/client_1.png">
<meta property="og:image" content="https://tony_df.coding.net/2018/10/08/一个简单的socket小工具/client_2.png">
<meta property="og:image" content="https://tony_df.coding.net/2018/10/08/一个简单的socket小工具/server_1.jpg">
<meta property="og:image" content="https://tony_df.coding.net/2018/10/08/一个简单的socket小工具/server_2.jpg">
<meta property="og:image" content="https://tony_df.coding.net/2018/10/08/一个简单的socket小工具/server_3.jpg">
<meta property="og:image" content="https://tony_df.coding.net/2018/10/08/一个简单的socket小工具/server_4.png">
<meta property="og:image" content="https://tony_df.coding.net/2018/10/08/一个简单的socket小工具/server_5.jpg">
<meta property="og:updated_time" content="2018-10-08T09:22:42.340Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="一个简单的socket小工具">
<meta name="twitter:description" content="最近公司赶项目，由于时间，人手等问题，经理武断的决定把一个本来要做成app的项目做成手机web网站的形式。。。然后还把这个项目交给了一个后端开发人员（没错就是我(┬＿┬)）。。。在做这个项目的是，由于采用的是webapi的形式和服务器交互，所以，这个手机web网站就是纯前端的东西，html+js。由于我对前端的项目部署方案不太了解，当我们需要把文件部署到服务器上测试的时候，每次都要远程连接服务器然">
<meta name="twitter:image" content="https://tony_df.coding.net/2018/10/08/一个简单的socket小工具/client_1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/hexo/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Tony'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://tony_df.coding.net/2018/10/08/一个简单的socket小工具/">





  <title>一个简单的socket小工具 | Tony's blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/hexo/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学着码代码,学着码人生;</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/hexo/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/hexo/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/hexo/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://tony_df.coding.net/hexo/2018/10/08/一个简单的socket小工具/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/hexo/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">一个简单的socket小工具</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-10-08T11:59:56+08:00">
                2018-10-08
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>最近公司赶项目，由于时间，人手等问题，经理武断的决定把一个本来要做成app的项目做成手机web网站的形式。。。然后还把这个项目交给了一个后端开发人员（没错就是我(┬＿┬)）。。。<br>在做这个项目的是，由于采用的是webapi的形式和服务器交互，所以，这个手机web网站就是纯前端的东西，html+js。由于我对前端的项目部署方案不太了解，当我们需要把文件部署到服务器上测试的时候，每次都要远程连接服务器然后<br>把修改后的文件包括html,js,css以及一些图片等文件分别拷贝到服务器去进行测试，这样每次操作下来非常麻烦，而且容易丢文件，即便是每次把整个文件夹都拷过去也还是需要每次都远程服务器，而且大多数时候是不可以整<br>个文件替换的，因为难免会有一些公用的js文件里写了一些服务器地址等相关配置的地方，和本地是不一样的，当然还有一种比较普遍的解决方式就是用ftp的形式来传输文件，也很方便，但总感觉还可以在方便一点，在灵活一点，<br>联想到以前曾经做过一个socket的项目，就自然而然想到用把之前的项目拿来，精简一下，只留下传输相关的部分，就自制了一个快速部署静态文件，传输文件，以及信息交互的小工具。<br>好了，话不多说，先看东西（当然很丑，没有界面只是控制台程序）<br><img src="client_1.png" alt="client_1"><br><img src="client_2.png" alt="client_2"><br>客户端的命令行界面，目前只支持这几种命令，可以无限扩展<del>，目前我需要的只是发送文件，发送压缩包和解压缩<br><img src="server_1.jpg" alt="server_1"><br><img src="server_2.jpg" alt="server_2"><br><img src="server_3.jpg" alt="server_3"><br><img src="server_4.png" alt="server_4"><br>服务端收到命令后，会执行相关命令，其中关于文件传输和解压缩的命令，在传输过程中，为了安全，需要在客户端和服务端代码中稍微做一下验证，比如我就加了一个“F_”来表示这是客户端发来的文件，<br>这里的文件解压用的是ICSharpCode.SharpZipLib插件，.net 环境下一个开源的也挺好用的文件压缩插件，推荐一下</del><br>当然还需要记录一下访问日志，这里用的是NLog插件</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">//发送[文件名]到客户端</span><br><span class="line">TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(&quot;F_&quot; + EzoneFile.Name));</span><br></pre></td></tr></table></figure>

<p>当然服务端接收的时候也要做相应的处理<br>还有因为接通外网的服务器端口是会被各种有意无意的扫描软件扫到的，所以用这个小工具的时候需要加一下ip验证，当然也可以做的更完善点，这个我就不多说了<br>对了，之所以做成控制台的形式，是我为了方便，可以做一个bat批处理文件，把它和服务端程序放在一起，把调用的参数写进去，做成服务，更加方便<br><img src="server_5.jpg" alt="server_5"><br>好了，直接上代码了<br>socket相关的关键代码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 发送数据包</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;s&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;data&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public static int SendVarData(Socket s, byte[] data)</span><br><span class="line">&#123;</span><br><span class="line">    int total = 0;</span><br><span class="line">    int size = data.Length;</span><br><span class="line">    int dataleft = size;</span><br><span class="line">    int sent;</span><br><span class="line">    byte[] datasize = new byte[4];</span><br><span class="line"></span><br><span class="line">    try</span><br><span class="line">    &#123;</span><br><span class="line">        datasize = BitConverter.GetBytes(size);</span><br><span class="line">        sent = s.Send(datasize);</span><br><span class="line"></span><br><span class="line">        while (total &lt; size)</span><br><span class="line">        &#123;</span><br><span class="line">            sent = s.Send(data, total, dataleft, SocketFlags.None);</span><br><span class="line">            total += sent;</span><br><span class="line">            dataleft -= sent;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        return total;</span><br><span class="line">    &#125;</span><br><span class="line">    catch</span><br><span class="line">    &#123;</span><br><span class="line">        return 3;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 接受数据包</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;s&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public static byte[] ReceiveVarData(Socket s)</span><br><span class="line">&#123;</span><br><span class="line">    int total = 0;</span><br><span class="line">    int recv;</span><br><span class="line">    byte[] datasize = new byte[4];</span><br><span class="line">    recv = s.Receive(datasize, 0, 4, SocketFlags.None);</span><br><span class="line">    int size = BitConverter.ToInt32(datasize, 0);</span><br><span class="line">    int dataleft = size;</span><br><span class="line">    byte[] data = new byte[size];</span><br><span class="line">    while (total &lt; size)</span><br><span class="line">    &#123;</span><br><span class="line">        recv = s.Receive(data, total, dataleft, SocketFlags.None);</span><br><span class="line">        if (recv == 0)</span><br><span class="line">        &#123;</span><br><span class="line">            data = null;</span><br><span class="line">            break;</span><br><span class="line">        &#125;</span><br><span class="line">        total += recv;</span><br><span class="line">        dataleft -= recv;</span><br><span class="line">    &#125;</span><br><span class="line">    return data;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>关键的上层调用类如下</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br></pre></td><td class="code"><pre><span class="line">using NLog;</span><br><span class="line">using System;</span><br><span class="line">using System.IO;</span><br><span class="line">using System.Net;</span><br><span class="line">using System.Net.Sockets;</span><br><span class="line"></span><br><span class="line">namespace SocketHelper</span><br><span class="line">&#123;</span><br><span class="line">    public class Common</span><br><span class="line">    &#123;</span><br><span class="line">        /// &lt;summary&gt;</span><br><span class="line">        /// 日志</span><br><span class="line">        /// &lt;/summary&gt;</span><br><span class="line">        private static readonly Logger logger = LogManager.GetCurrentClassLogger();</span><br><span class="line"></span><br><span class="line">        /// &lt;summary&gt;</span><br><span class="line">        /// 控制台单行输出，同时生成日志文件</span><br><span class="line">        /// &lt;/summary&gt;</span><br><span class="line">        /// &lt;param name=&quot;msg&quot;&gt;&lt;/param&gt;</span><br><span class="line">        /// &lt;param name=&quot;level&quot;&gt;&lt;/param&gt;</span><br><span class="line">        public static void ConsoleM(string msg, int level=0)</span><br><span class="line">        &#123;</span><br><span class="line">            string content = string.Format(&quot;&#123;0&#125;-&#123;1&#125;&quot;, DateTime.Now, msg);</span><br><span class="line">            switch (level)</span><br><span class="line">            &#123;</span><br><span class="line">                case 0:</span><br><span class="line">                    logger.Debug(msg);</span><br><span class="line">                    break;</span><br><span class="line">                case 1:</span><br><span class="line">                    logger.Info(msg);</span><br><span class="line">                    break;</span><br><span class="line">                case 2:</span><br><span class="line">                    logger.Warn(msg);</span><br><span class="line">                    break;</span><br><span class="line">                case 3:</span><br><span class="line">                    logger.Error(msg);</span><br><span class="line">                    break;</span><br><span class="line">                case 4:</span><br><span class="line">                    logger.Fatal(msg);</span><br><span class="line">                    break;</span><br><span class="line">                default:</span><br><span class="line">                    logger.Debug(msg);</span><br><span class="line">                    break;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            Console.WriteLine(content);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public static bool SendFile(string IP, int Port, string fullPath)</span><br><span class="line">        &#123;</span><br><span class="line">            //创建一个文件对象</span><br><span class="line">            FileInfo EzoneFile = new FileInfo(fullPath);</span><br><span class="line">            //打开文件流</span><br><span class="line">            FileStream EzoneStream = EzoneFile.OpenRead();</span><br><span class="line">            //包的大小</span><br><span class="line">            int PacketSize = 10000;</span><br><span class="line">            //包的数量</span><br><span class="line">            int PacketCount = (int)(EzoneStream.Length / ((long)PacketSize));</span><br><span class="line">            //最后一个包的大小</span><br><span class="line">            int LastDataPacket = (int)(EzoneStream.Length - ((long)(PacketSize * PacketCount)));</span><br><span class="line">            //指向远程服务端节点</span><br><span class="line">            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(IP), Port);</span><br><span class="line">            //创建套接字</span><br><span class="line">            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);</span><br><span class="line">            //连接到发送端</span><br><span class="line">            try</span><br><span class="line">            &#123;</span><br><span class="line">                client.Connect(ipep);</span><br><span class="line">                Common.ConsoleM(&quot;connect...ok!&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">            catch</span><br><span class="line">            &#123;</span><br><span class="line">                Common.ConsoleM(&quot;连接服务器失败！&quot;);</span><br><span class="line">                return false;</span><br><span class="line">            &#125;</span><br><span class="line">            //获得客户端节点对象</span><br><span class="line">            IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;</span><br><span class="line">            //发送[文件名]到客户端</span><br><span class="line">            TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(&quot;F_&quot; + EzoneFile.Name));</span><br><span class="line">            //发送[包的大小]到客户端</span><br><span class="line">            TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketSize.ToString()));</span><br><span class="line">            //发送[包的总数量]到客户端</span><br><span class="line">            TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketCount.ToString()));</span><br><span class="line">            //发送[最后一个包的大小]到客户端</span><br><span class="line">            TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(LastDataPacket.ToString()));</span><br><span class="line">            bool isCut = false;</span><br><span class="line">            //数据包</span><br><span class="line">            byte[] data = new byte[PacketSize];</span><br><span class="line">            int cnt = 0;</span><br><span class="line">            //开始循环发送数据包</span><br><span class="line">            for (int i = 0; i &lt; PacketCount; i++)</span><br><span class="line">            &#123;</span><br><span class="line">                //从文件流读取数据并填充数据包</span><br><span class="line">                EzoneStream.Read(data, 0, data.Length);</span><br><span class="line">                //发送数据包</span><br><span class="line">                if (TransferFiles.SendVarData(client, data) == 3)</span><br><span class="line">                &#123;</span><br><span class="line">                    isCut = true;</span><br><span class="line">                    return false;</span><br><span class="line">                &#125;</span><br><span class="line">                System.Threading.Thread.Sleep(100);</span><br><span class="line">                Console.WriteLine(&quot;                    &quot;);</span><br><span class="line">                Console.SetCursorPosition(0, Console.CursorTop - 1);</span><br><span class="line">                float percent = i * 100 / PacketCount;</span><br><span class="line">                cnt = i;</span><br><span class="line">                Console.Write(DateTime.Now + &quot;-已发送&quot; + cnt + &quot;个包,共有&quot; + PacketCount + &quot;个包&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">            //如果还有多余的数据包，则应该发送完毕！</span><br><span class="line">            if (LastDataPacket != 0)</span><br><span class="line">            &#123;</span><br><span class="line">                data = new byte[LastDataPacket];</span><br><span class="line">                EzoneStream.Read(data, 0, data.Length);</span><br><span class="line">                TransferFiles.SendVarData(client, data);</span><br><span class="line">            &#125;</span><br><span class="line">            if (cnt &lt; PacketCount)</span><br><span class="line">            &#123;</span><br><span class="line">                Console.WriteLine(&quot;&quot;);</span><br><span class="line">                Common.ConsoleM(&quot;余量包发送完毕，共计发送&quot; + PacketCount + &quot;个数据包&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">            //关闭套接字</span><br><span class="line">            client.Close();</span><br><span class="line">            //关闭文件流</span><br><span class="line">            EzoneStream.Close();</span><br><span class="line">            if (!isCut)</span><br><span class="line">            &#123;</span><br><span class="line">                return true;</span><br><span class="line">            &#125;</span><br><span class="line">            return false;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public static bool SendMsg(string IP, int Port, string Msg)</span><br><span class="line">        &#123;</span><br><span class="line">            //指向远程服务端节点</span><br><span class="line">            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(IP), Port);</span><br><span class="line">            //创建套接字</span><br><span class="line">            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);</span><br><span class="line">            //连接到发送端</span><br><span class="line">            try</span><br><span class="line">            &#123;</span><br><span class="line">                client.Connect(ipep);</span><br><span class="line">                //Common.ConsoleM(&quot;connect...ok!&quot;);</span><br><span class="line">                TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(Msg));</span><br><span class="line">                while (true)</span><br><span class="line">                &#123;</span><br><span class="line">                    string ret = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));</span><br><span class="line">                    if (!string.IsNullOrEmpty(ret))</span><br><span class="line">                    &#123;</span><br><span class="line">                        Common.ConsoleM(ret);</span><br><span class="line">                        break;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            catch</span><br><span class="line">            &#123;</span><br><span class="line">                Common.ConsoleM(&quot;连接服务器失败！&quot;);</span><br><span class="line">                return false;</span><br><span class="line">            &#125;</span><br><span class="line">            return true;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public static void Command_File(string ip, int port)</span><br><span class="line">        &#123;</span><br><span class="line">            Common.ConsoleM(string.Format(&quot;进入传输文件模式，服务器地址为&#123;0&#125;，端口为&#123;1&#125;，请输入文件完整路径&quot;, ip, port));</span><br><span class="line">            while (true)</span><br><span class="line">            &#123;</span><br><span class="line">                string fullPath = Console.ReadLine();</span><br><span class="line">                if (fullPath == &quot;exit&quot;)</span><br><span class="line">                &#123;</span><br><span class="line">                    Common.ConsoleM(&quot;已退出文件传输模式&quot;);</span><br><span class="line">                    break;</span><br><span class="line">                &#125;</span><br><span class="line">                if (File.Exists(fullPath))</span><br><span class="line">                &#123;</span><br><span class="line">                    Common.ConsoleM(&quot;开始传输...&quot;);</span><br><span class="line">                    Common.SendFile(ip, port, fullPath);</span><br><span class="line">                    //break;</span><br><span class="line">                &#125;</span><br><span class="line">                else</span><br><span class="line">                &#123;</span><br><span class="line">                    Common.ConsoleM(&quot;路径不合法或文件不存在&quot;);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>好了大概就是这个样子，至于客户端和服务端交互上，我就不贴代码了，非常简单，而且我写的风格也没啥参考价值，最多就是多了一个思路，大家完全可以自己改造。完整代码在这→<a href="https://gitee.com/Tony_df/SocketProject" target="_blank" rel="noopener">https://gitee.com/Tony_df/SocketProject</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/hexo/tags/经验分享/" rel="tag"># 经验分享</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/hexo/2018/08/28/接口知识总结（转）/" rel="next" title="接口知识总结（转）">
                <i class="fa fa-chevron-left"></i> 接口知识总结（转）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/hexo/2018/10/23/实则害了自己/" rel="prev" title="实则害了自己">
                实则害了自己 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_inline_share_toolbox">
  <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5bbb2338b87602f0" async="async"></script>
</div>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zOTA1My8xNTU4MA"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Tony</p>
              <p class="site-description motion-element" itemprop="description">学习总结</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/hexo/archives/">
              
                  <span class="site-state-item-count">58</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/hexo/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/hexo/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/hexo/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/hexo/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/hexo/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/hexo/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/hexo/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

</body>
</html>
